package com.my.algorithmlearning.leetcode;

import org.springframework.util.Assert;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName Medium_128_LongestConsecutive
 * @Description 参考题解：https://leetcode.cn/problems/longest-consecutive-sequence/solution/dong-tai-gui-hua-python-ti-jie-by-jalan/
 * @Author wanghaiwei
 * @Date 2023/4/6 14:25
 */
public class Medium_128_LongestConsecutive {

    public int longestConsecutive(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        if (nums.length == 1) {
            return 1;
        }
        int result = 0;
        Map<Integer, Integer> radiateLength = new HashMap<>();
        for (int numI : nums) {
            if (radiateLength.containsKey(numI)) {
                continue;
            }
            int leftLen = radiateLength.getOrDefault(numI - 1, 0);
            int rightLen = radiateLength.getOrDefault(numI + 1, 0);
            int currNumRadiateLength = 1 + leftLen + rightLen;
            if (currNumRadiateLength > result) {
                result = currNumRadiateLength;
            }
            radiateLength.put(numI, currNumRadiateLength);
            radiateLength.put(numI - leftLen, currNumRadiateLength);
            radiateLength.put(numI + rightLen, currNumRadiateLength);
        }
        return result;
    }

    public static void main(String[] args) {
        Medium_128_LongestConsecutive solution = new Medium_128_LongestConsecutive();
        int result = solution.longestConsecutive(new int[]{100, 4, 200, 1, 3, 2});
        Assert.isTrue(result == 4, "Input: nums = [100,4,200,1,3,2] 计算错误，预期：4，实际：" + result);
        result = solution.longestConsecutive(new int[]{0, 3, 7, 2, 5, 8, 4, 6, 0, 1});
        Assert.isTrue(result == 9, "Input: nums = [0,3,7,2,5,8,4,6,0,1] 计算错误，预期：9，实际：" + result);
        result = solution.longestConsecutive(new int[]{1, 2, 0, 1});
        Assert.isTrue(result == 3, "Input: nums = [1,2,0,1] 计算错误，预期：3，实际：" + result);
    }
}
